package cn.wolfcode.ssm.web.interceptor;

import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.service.IEmployeeService;
import cn.wolfcode.ssm.service.IPermissionService;
import cn.wolfcode.ssm.util.RequireAnnotation;
import cn.wolfcode.ssm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //先获取员工信息
        Employee employee = UserContext.getEmployee();
        //判断是否为管理员
        if (employee.isAdmin()) {
            return true;//是管理员就放行
        }
        //（先判断是否为处理方法）获取被拦截的处理方法
        if(!(handler instanceof HandlerMethod)){
            return true;//不是处理方法就放行
        }
        //对处理方法进行强转
        HandlerMethod method = (HandlerMethod) handler;
        //判断该处理方法是否贴有自定义权限注解
        RequireAnnotation annotation = method.getMethodAnnotation(RequireAnnotation.class);
        if(annotation == null){
            return true;//没有自定义注解则放行
        }
        //从数据库中查询出该员工的拥有的权限信息（通过查询员工的角色，再通过角色查询出对应的权限表达式）
        //List<String> expressions = permissionService.selectForExpressionById(employee.getId());
        //直接从Session中获取该员工的权限表达式集合
        //List<String> expressions = (List<String>)request.getSession().getAttribute(UserContext.PERMISSIONS_IN_SESSION);

        List<String> expressions = UserContext.getPermission();
        //判断该处理方法的注解是否包含在查出的权限集合List中
        if (expressions.contains(annotation.expression())){
            return true;//有权限则放行
        }
        //跳转无权限访问页面（通过重定向到控制器再访问视图）
        //request.getRequestDispatcher("").forward(request,response);
        response.sendRedirect("/employee/nopermission");
        return false;
    }
}
